package com.airport.ticket.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.airport.ticket.entity.FlightInfoEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.airport.ticket.common.DateUtil;
import com.airport.ticket.common.UrlUtil;
import com.airport.ticket.dao.FlightInfoMapper;
import com.airport.ticket.dao.OrderInfoMapper;
import com.airport.ticket.dao.UserInfoMapper;
import com.airport.ticket.entity.FlightInfo;
import com.airport.ticket.entity.FlightInfoExample;
import com.airport.ticket.entity.FlightInfoExample.Criteria;
import com.airport.ticket.entity.OrderInfo;
import com.airport.ticket.entity.UserInfo;
import com.airport.ticket.entity.UserInfoExample;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping("/admin")
public class BuyTicketController {

    @Autowired
    private FlightInfoMapper flightInfoMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private HttpServletRequest request;

    @RequestMapping(value = "/buyticket.html")
    public String buyTicket(ModelMap map, String keyword, String departurePlace, String arrivalPlace, String departureDate,String errorMsg) {
        map.addAttribute("nav", "5");
        map.addAttribute("title", "购买机票");
        map.addAttribute("keyword", keyword);
        map.addAttribute("departurePlace", departurePlace);
        map.addAttribute("arrivalPlace", arrivalPlace);
        map.addAttribute("departureDate", departureDate);

        if (errorMsg != null && !"".equals(errorMsg)) {
            map.addAttribute("errorMsg", errorMsg);
        }

        Map<String,Object> condMap = new HashMap<>();
        FlightInfoExample condition = new FlightInfoExample();
        Criteria ct = condition.createCriteria();
        /**
         * 只获取出发时间大于当前时间的航班
         */
        ct.andDepartureTimeGreaterThanOrEqualTo(new Date());

        if (keyword != null && !"".equals(keyword)) {
            ct.andFlightNumberLike("%" + keyword + "%");
        }
        if (departurePlace != null && !"".equals(departurePlace)) {
            ct.andDeparturePlaceEqualTo(departurePlace);
            condMap.put("departurePlace", departurePlace);
        }
        if (arrivalPlace != null && !"".equals(arrivalPlace)) {
            ct.andArrivalPlaceEqualTo(arrivalPlace);
            condMap.put("arrivalPlace", arrivalPlace);
        }
        if (departureDate != null && !"".equals(departureDate)) {
            Date beginDate = DateUtil.parseToDate(departureDate + " 00:00:00");
            Date endDate = DateUtil.parseToDate(departureDate + " 23:59:59");
            ct.andDepartureTimeGreaterThanOrEqualTo(beginDate);
            ct.andDepartureTimeLessThanOrEqualTo(endDate);

            condMap.put("departureTime", departureDate);
        }
        condition.setOrderByClause("id DESC");
        List<FlightInfo> resultList = flightInfoMapper.selectByExample(condition);
        if (!condMap.isEmpty()) {
            /* 查询中转数据 */
            List<FlightInfo> zhongInfoList = this.flightInfoMapper.selectCondUnionList(condMap);
            for (FlightInfo flightInfo : zhongInfoList) {
                flightInfo.setDirectTypeNum(1);
                flightInfo.setDirectTypeStr(FlightInfoEnum.DIRECTTYPE_ZHONGZHUAN.getName());
                resultList.add(flightInfo);
            }
        }

        if (resultList == null || resultList.size() == 0) {
            map.addAttribute("retCode", "99");
            map.addAttribute("totalPage", "0");
            return "admin/ticket/buy_ticket";
        }
        map.addAttribute("resultList", resultList);
        return "admin/ticket/buy_ticket";
    }

    /**
     * 中转
     * @param map
     * @param errorMsg
     * @return
     */
    @RequestMapping(value = "/buyticketZhuanList.html")
    public String buyticketZhuanList(ModelMap map, int fromId, int toId,String errorMsg) {
        map.addAttribute("nav", "5");
        map.addAttribute("title", "换乘记录");

        if (errorMsg != null && !"".equals(errorMsg)) {
            map.addAttribute("errorMsg", errorMsg);
        }

        Map<String,Object> condMap = new HashMap<>();
        FlightInfoExample condition = new FlightInfoExample();
        Criteria ct = condition.createCriteria();
        /**
         * 只获取出发时间大于当前时间的航班
         */
        ct.andDepartureTimeGreaterThanOrEqualTo(new Date());

        FlightInfo from = flightInfoMapper.selectByPrimaryKey(fromId);
        FlightInfo to = flightInfoMapper.selectByPrimaryKey(toId);

        List<FlightInfo> resultList = new ArrayList<>();
        resultList.add(from);
        resultList.add(to);

        if (resultList == null || resultList.size() == 0) {
            map.addAttribute("retCode", "99");
            map.addAttribute("totalPage", "0");
            return "admin/ticket/buy_ticket";
        }
        map.addAttribute("resultList", resultList);
        return "admin/ticket/buyticketZhuanList";
    }

    @RequestMapping(value = "/do_buy_ticket.html")
    public String doUpdateflight(ModelMap map, FlightInfo flight) {
        map.addAttribute("nav", "5");
        map.addAttribute("title", "购买机票");

        /**
         * 判断航班是否存在
         */
        FlightInfo flightInfo = flightInfoMapper.selectByPrimaryKey(flight.getId());
        if (flightInfo == null || flightInfo.getId() == null || "".equals(flightInfo.getId())) {
            return "redirect:/admin/buyticket.html?errorMsg=" + UrlUtil.parseUtf8("购买失败，航班不存在");
        }

        HttpSession session = request.getSession();
        UserInfo loginUserInfo = (UserInfo) session.getAttribute("loginUserInfo");

        /**
         * 查当前登录用户
         */
        UserInfo thisUser = userInfoMapper.selectByPrimaryKey(loginUserInfo.getId());

        /**
         * 判断是否够钱买机票
         */
        if (thisUser.getAmount().compareTo(flightInfo.getPrice()) < 0) {
            return "redirect:/admin/buyticket.html?errorMsg=" + UrlUtil.parseUtf8("购买失败，余额不足，请先充值");
        }

        /**
         * 够钱买，扣掉用户的钱
         */
        thisUser.setAmount(thisUser.getAmount().subtract(flightInfo.getPrice()));
        userInfoMapper.updateByPrimaryKey(thisUser);

        /**
         * 更新session
         */
        session.setAttribute("loginUserInfo", thisUser);

        /**
         * 够钱买，则创建订单
         */
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setFlightId(flightInfo.getId());
        orderInfo.setUserId(thisUser.getId());
        orderInfo.setStatus("1");//已支付
        orderInfo.setCreateTime(new Date());
        orderInfoMapper.insert(orderInfo);

        map.addAttribute("orderInfo", orderInfo);
        map.addAttribute("flightInfo", flightInfo);

        return "admin/ticket/buy_finish";
    }

}
